package com.neusoft.elm.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库连接测试工具
 */
public class DatabaseTest {
    
    public static void main(String[] args) {
        testDatabaseConnection();
        testBusinessTable();
    }
    
    /**
     * 测试数据库连接
     */
    public static void testDatabaseConnection() {
        System.out.println("=== 测试数据库连接 ===");
        
        try {
            Connection conn = DBUtil.getConnection();
            if (conn != null && !conn.isClosed()) {
                System.out.println("✓ 数据库连接成功");
                System.out.println("数据库URL: " + conn.getMetaData().getURL());
                System.out.println("数据库用户: " + conn.getMetaData().getUserName());
            } else {
                System.out.println("✗ 数据库连接失败");
            }
        } catch (Exception e) {
            System.out.println("✗ 数据库连接异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
    }
    
    /**
     * 测试商家表查询
     */
    public static void testBusinessTable() {
        System.out.println("\n=== 测试商家表查询 ===");
        
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        
        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT COUNT(*) as count FROM business";
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            
            if (rs.next()) {
                int count = rs.getInt("count");
                System.out.println("✓ 商家表查询成功，共有 " + count + " 条记录");
                
                if (count > 0) {
                    // 查询前3条记录
                    String detailSql = "SELECT businessId, businessName, rating, monthlySales, distance FROM business LIMIT 3";
                    PreparedStatement detailPst = conn.prepareStatement(detailSql);
                    ResultSet detailRs = detailPst.executeQuery();
                    
                    System.out.println("前3条商家记录:");
                    while (detailRs.next()) {
                        System.out.println(String.format("ID: %d, 名称: %s, 评分: %.1f, 销量: %d, 距离: %.1f",
                            detailRs.getInt("businessId"),
                            detailRs.getString("businessName"),
                            detailRs.getDouble("rating"),
                            detailRs.getInt("monthlySales"),
                            detailRs.getDouble("distance")
                        ));
                    }
                    detailRs.close();
                    detailPst.close();
                }
            }
        } catch (Exception e) {
            System.out.println("✗ 商家表查询异常: " + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(rs, pst);
            DBUtil.close();
        }
    }
}